package za.co.dylanjaneke.airdownloader.command
{
	import flash.events.Event;
	
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import za.co.dylanjaneke.airdownloader.events.LoadTrackedShowsEvent;
	import za.co.dylanjaneke.airdownloader.events.LoginEvent;
	import za.co.dylanjaneke.airdownloader.model.ScreenNavigatorPM;
	import za.co.dylanjaneke.airdownloader.model.StatusPM;
	import za.co.dylanjaneke.airdownloader.model.TrackerSettingsScreenPM;

	/**
	 * Author: Dylan Janeke.
	 */
	[Name("loginCommand")]
	public class LoginCommand
	{
		[Inject]
		public var settingsPM:TrackerSettingsScreenPM;
		
		[Inject]
		public var statusPM:StatusPM;
		
		[Inject]
		public var screenNavigatorPM:ScreenNavigatorPM;
		
		[Observer]
		public function handleLoginEvent(event:LoginEvent): void
		{
			var loginService:HTTPService= new HTTPService();
			
			loginService.addEventListener(ResultEvent.RESULT, onAuthResult);
			loginService.addEventListener(FaultEvent.FAULT, onAuthFault);
			loginService.url= "http://www.sidereel.com/users/sign_in.json";
			loginService.method= "POST";
			
			var credObj:Object= new Object();
			credObj["user[email]"]= settingsPM.vo.username;
			credObj["user[password]"]= settingsPM.vo.password;
			
			loginService.send(credObj);
		}
		
		protected function onAuthFault(event:FaultEvent): void
		{
			Alert.show(event.fault.faultDetail, event.fault.faultString);
		}
		
		protected function onAuthResult(event:ResultEvent): void
		{
			if(event.result!="{\"success\":true}"||
				(event.result as String).indexOf("\"success\":false") > -1)
			{
				Alert.show("Sidereel Authentication failed with the message:\n"+ 
					(event.result as String), "Authentication Failed.");
				statusPM.status= "authentication failed";
				screenNavigatorPM.switchView(ScreenNavigatorPM.SETTINGS);
				return;
			}
			
			statusPM.status= "logged in";
			
			GlobalEventDispatcher.raiseEvent(new LoadTrackedShowsEvent());
		}
	}
}